package fun.xinnix.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.extra.validation.ValidationUtil;
import dto.ValidDto;
import fun.xinnix.entity.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ValidationException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import valid.ValidGroupOne;
import valid.ValidGroupThree;
import valid.ValidGroupTwo;

import java.util.Set;


@RequestMapping("/valid")
@RestController
@Validated
public class ValidController {
    @PostMapping("testSwitch")
    public Result testSwitch(@RequestBody ValidDto dto) {
        Set<ConstraintViolation<ValidDto>> validateResult = null;
        if (dto.getKey().equals("one")) {
            validateResult = ValidationUtil.validate(dto, ValidGroupOne.class);
        }
        if (dto.getKey().equals("two")) {
            validateResult = ValidationUtil.validate(dto, ValidGroupTwo.class);
        }
        if (dto.getKey().equals("three")) {
            validateResult = ValidationUtil.validate(dto, ValidGroupThree.class);
        }
        if (CollectionUtil.isNotEmpty(validateResult)) {
            ConstraintViolation<ValidDto> next = validateResult.iterator().next();
            throw new ValidationException(next.getMessageTemplate());
        }
        Console.log(validateResult);
        return Result.success(dto);
    }

    @PostMapping("testOne")
    public Result testOne(@RequestBody @Validated({ValidGroupOne.class}) ValidDto dto) {
        Console.log(dto);
        return Result.success(dto);
    }

    @PostMapping("testTwo")
    public Result testTwo(@RequestBody @Validated({ValidGroupTwo.class}) ValidDto dto) {
        Console.log(dto);
        return Result.success(dto);
    }

    @PostMapping("testThree")
    public Result testThree(@RequestBody @Validated({ValidGroupThree.class}) ValidDto dto) {
        Console.log(dto);
        return Result.success(dto);
    }
}
